<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="../js/vue2-dev.js"></script>
    </head>
    <body>
        <!-- 
            给列表进行排序展示
                1.给定persons初始数据、keyword搜索关键字、排序类型
                2.通过计算属性计算过滤后的新数组personFilter
                3.在关键字搜索的基础上加入根据排序种类进行排序处理
                4.排序处理通过的是arr.sort((o1,o2)=>{return o1.age-o2.age})实现的
                5.由于计算属性中判断了排序种类，所以只要排序种类变量发生了改变就会重新计算personFilter
         -->

        <div id="root">
            <input v-model="keyword" type="text" />
            <button @click="sortNum = 0">原顺序</button>
            <button @click="sortNum = 1">升序</button>
            <button @click="sortNum = 2">降序</button>
            <ul>
                <li v-for="(person, index) in personFilter" :key="index">
                    {{person.name}}--{{person.age}}
                </li>
            </ul>
        </div>

        <script>
            const vm = new Vue({
                data() {
                    return {
                        // 0代表不排序，1代表升序，2代表降序
                        sortNum: 0,
                        keyword: "",
                        persons: [
                            { name: "马冬梅", age: 26 },
                            { name: "周冬雨", age: 22 },
                            { name: "周杰伦", age: 23 },
                            { name: "温兆伦", age: 19 },
                        ],
                    };
                },
                computed: {
                    personFilter() {
                        const arr = this.persons.filter((person) => {
                            return person.name.indexOf(this.keyword) != -1;
                        });
                        if (this.sortNum) {
                            arr.sort((p1, p2) => {
                                return this.sortNum == 1
                                    ? p1.age - p2.age
                                    : p2.age - p1.age;
                            });
                        }
                        return arr;
                    },
                },
            });

            vm.$mount("#root");
        </script>
    </body>
</html>
